#!/bin/sh /etc/rc.common
# Copyright (C) 2006-2011 OpenWrt.org

START=50
USE_PROCD=1

LOGFILE="/tmp/nps.log"
tmpconf="/tmp/etc/nps.conf"

nps_header() {
	local enabled server_addr server_port protocol vkey compress crypt log_level

	config_get enabled $1 enabled
	config_get server_addr $1 server_addr
	config_get server_port $1 server_port
	config_get protocol $1 protocol
	config_get vkey $1 vkey
	config_get compress $1 compress
	config_get crypt $1 crypt
	config_get log_level $1 log_level

	[ -f $tmpconf ] && rm $tmpconf
	echo "[common]" >$tmpconf
	echo "server_addr=${server_addr}:${server_port}" >>$tmpconf
	echo "conn_type=${protocol}" >>$tmpconf
	echo "vkey=${vkey}" >>$tmpconf
	echo "auto_reconnection=true" >>$tmpconf

	nps_write_bool compress $1
	nps_write_bool crypt $1

	Log_level=$log_level
	Enabled=$enabled
}

nps_write_bool() {
	local opt="$1"
	local config="$2"
	local val

	config_get_bool val $config "$opt"
	if [ "$val" -eq 0 ]; then
		echo "${opt}=false" >> $tmpconf
	else
		echo "${opt}=true" >> $tmpconf
	fi
}

start_service() {
	config_load nps
	config_foreach nps_header nps

	if [ "$Enabled" = "1" ];then
		logger -t FRPC 'Starting Nps service' 
		procd_open_instance
    		procd_set_param command /usr/bin/npc -config=$tmpconf -log_level=$Log_level -log_path=$LOGFILE
    		#procd_set_param file $tmpconf
    		procd_set_param respawn
    		procd_set_param stdout 1
    		procd_set_param stderr 1
    		procd_close_instance
	fi
}

service_triggers() {
        procd_add_reload_trigger "nps"
}
